class Artwork < ActiveRecord::Base
  belongs_to :artist
  has_many :medias
  has_many :cart_items
  has_many :carts, :through => :cart_items
  has_many :orders, :through => :artwork_order
  has_many :artwork_descriptions
  has_and_belongs_to_many :categories
  
  validates_presence_of :name
  validates_numericality_of :price
  validates_presence_of :artist_id
  
  def self.full_list(page)
    paginate :per_page => 10, :page => page, :order => 'artworks.name'
  end
    
  def convert_to(units)
    raise "NotImplemented"
  end
  
  acts_as_ferret :fields => [:name]
  
  def add_category(cat)
    if !self.categories.include? cat
      self.categories << cat
      self.save
    end 
  end
  
  def get_single_desc
    desc = ArtworkDescription.find(:first, :conditions => {:artwork_id => self.id, :language => "English"})
    return desc unless desc.nil?
    desc =  ArtworkDescription.find_by_artwork_id(self.id);
    return desc unless desc.nil?
    ArtworkDescription.new
  end
  
  class Weight
    UNITS_POUNDS = 1
    UNITS_KILOGRAMS = 2
    UNITS_OUNCES = 3
    UNITS_GRAMS = 4
    
    OPTIONS = [[l(:units, 'pounds'), UNITS_POUNDS],
            [l(:units, 'kilograms'), UNITS_KILOGRAMS],
            [l(:units, 'ounces'), UNITS_OUNCES],
            [l(:units, 'grams'), UNITS_GRAMS]]
    
    # For class use only (would be Private if that worked)
    KILOGRAMS_PER_POUND = 0.45359237
    OUNCES_PER_POUND = 16.0
    GRAMS_PER_POUND = 453.59237
    
=begin
  Convert between units of weight using class constants
=end
    class << self
      
      def convert(amount, from, to)
        if from == UNITS_POUNDS || to == UNITS_POUNDS
          if from == UNITS_POUNDS
            operand = Proc.new {|val1, val2|
              val1 * val2
            }
            other = to
          else
            operand = Proc.new {|val1, val2|
              val1 / val2
            }
            other = from
          end
          
          case other
            when UNITS_POUNDS
              return amount
            when UNITS_KILOGRAMS
              return operand.call(amount, KILOGRAMS_PER_POUND)
            when UNITS_OUNCES
              return operand.call(amount, OUNCES_PER_POUND)
            when UNITS_GRAMS
              return operand.call(amount, GRAMS_PER_POUND)
            else
              raise
          end
        else
          convert(convert(amount, from, UNITS_POUNDS), UNITS_POUNDS, to)
        end
      end
    end
  end
  
  def to_param
    id.to_s + '-' + CGI.escape(name.downcase.gsub(' ', '-'))
  end
  
  def dollar_amount
    format "%0.02f", price
  end
  
  def first_thumb 
    picture = medias.select {|m| m.is_a? Picture}.first
    '/picture/file/' + picture.file_relative_path("thumb")
  end
  
  include AdminHelper
  def unpublish_if_necessary
    check_requirements :artwork, self
    if self.published && !meets_requirements?
      self.published = false
      self.save
      true
    else
      false
    end
  end
end